package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.data.Result;
import com.dongdong.em.ResultEmnu;
import com.dongdong.exception.LoginException;
import com.dongdong.pojo.TPerson;
import com.dongdong.pojo.TbSeller;
import com.dongdong.service.SellerService;
import com.dongdong.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("seller")
public class SellerController {
    @Reference
    private SellerService sellerService;
    @RequestMapping("toLogin")
    public String toLogin(){
        return "shoplogin";
    }
    @RequestMapping("checkPhone")
    @ResponseBody
    public boolean checkPhone(String sellerId){
       return sellerService.selectSellerId(sellerId);
    }
    @RequestMapping("login")
    public String loginInfo(TbSeller seller, Model model){
        if (seller.getSellerId() == null || "".equals(seller.getSellerId()) || seller.getPassword() == null || "".equals(seller.getPassword())){
            model.addAttribute("message","请输入正确的账号密码");
            return "shoplogin";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(seller.getSellerId(),seller.getPassword());
        try{
            subject.login(token);
        }catch (UnknownAccountException e1){
            //账号不存在
            model.addAttribute("message","账号不存在");
            return "shoplogin";
        }catch (IncorrectCredentialsException e2){
            //密码错误
            model.addAttribute("message","密码错误");
            return "shoplogin";
        }catch (LoginException loginException) {
            loginException.printStackTrace();
            //账号审核尚未通过
            model.addAttribute("message", "账号审核未通过");
            return "shoplogin";
        }
        return "redirect:/index";
    }
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }
    @RequestMapping("insertInfo")
    @ResponseBody
    public Result insertInfo(TbSeller tbSeller){
        //注册加密撒盐
        System.out.println(tbSeller.getSellerId());
        //获取所撒盐的长度
        String salt = "a81b7c";
        String md5 = ShiroUtils.encryptPassword("MD5",tbSeller.getPassword(),salt,3);
        //存储所加的盐
       /* tbSeller.setSalt(s);*/
        tbSeller.setPassword(md5);
        int i = sellerService.addSellerInfo(tbSeller);
        if (i>0){
            return Result.respone(ResultEmnu.SUCCESS);
        }
        return Result.respone(ResultEmnu.ERROR);
    }


}
